#!/usr/bin/python3
# -*- coding: utf-8 -*-

import uuid
import sqlite3
from datetime import datetime
from flask import current_app

class TokenService:
    """Token管理服务"""
    
    # 存储已生成的token，用于验证（内存缓存）
    _tokens = {}
    
    @classmethod
    def generate_token(cls):
        """生成随机token
        
        Returns:
            生成的token字符串
        """
        return str(uuid.uuid4()).replace('-', '')
    
    @classmethod
    def create_token(cls, user_info=None):
        """创建包含token的成功响应
        
        Args:
            user_info: 用户信息，可选
            
        Returns:
            token字符串和包含token的字典
        """
        # 使用generate_token方法生成随机token
        token = cls.generate_token()
        
        # 存储token到内存
        cls._tokens[token] = user_info or {}
        
        # 如果有用户名，则将token保存到数据库
        username = user_info.get('username') if user_info else None
        if username and username != 'admin':
            try:
                conn = sqlite3.connect(current_app.config['DB_PATH'])
                cursor = conn.cursor()
                cursor.execute('UPDATE users SET token = ? WHERE username = ?', (token, username))
                conn.commit()
                conn.close()
                print(f"Token已保存到用户 {username} 的数据库记录")
            except Exception as e:
                print(f"保存token到数据库出错: {str(e)}")
        
        data = {"token": token}
        
        return token, data
    
    @classmethod
    def validate_token(cls, token):
        """验证token是否有效
        
        Args:
            token: 待验证的token字符串
            
        Returns:
            (bool, dict): (是否有效, 用户信息或错误消息)
        """
        if not token:
            return False, {"message": "未提供Token"}
        
        # 首先从内存中检查
        if token in cls._tokens:
            return True, cls._tokens[token]
        
        # 如果内存中不存在，从数据库检查
        try:
            conn = sqlite3.connect(current_app.config['DB_PATH'])
            cursor = conn.cursor()
            
            # 首先检查token是否存在于数据库中
            cursor.execute('SELECT username FROM users WHERE token = ?', (token,))
            result = cursor.fetchone()
            
            if not result:
                return False, {"message": "Token无效或已过期"}
                
            username = result[0]
            
            # 获取用户完整信息
            cursor.execute('''
            SELECT id, user_id, username, email, name, age, gender, address, phone, 
                   birthday, company, job, website, created_time, updated_time 
            FROM users 
            WHERE username = ?
            ''', (username,))
            
            user = cursor.fetchone()
            conn.close()
            
            if user:
                # 将数据库查询结果转换为字典
                columns = ['id', 'user_id', 'username', 'email', 'name', 'age', 'gender', 
                          'address', 'phone', 'birthday', 'company', 'job', 'website', 
                          'created_time', 'updated_time']
                           
                user_data = {columns[i]: user[i] for i in range(len(columns))}
                
                # 为了提高性能，将用户信息缓存到内存中
                cls._tokens[token] = user_data
                
                # 添加默认角色
                user_data['roles'] = ['user']
                
                return True, user_data
            else:
                return False, {"message": "Token对应的用户信息不完整"}
        except Exception as e:
            print(f"验证token出错: {str(e)}")
            return False, {"message": f"验证Token时发生错误: {str(e)}"}
    
    @classmethod
    def get_user_by_token(cls, token):
        """根据token获取用户信息
        
        Args:
            token: 用户token
            
        Returns:
            dict: 用户信息或None
        """
        is_valid, result = cls.validate_token(token)
        if is_valid:
            return result
        return None
    
    @classmethod
    def remove_token(cls, token):
        """移除token
        
        Args:
            token: 要移除的token
            
        Returns:
            bool: 是否成功移除
        """
        if token in cls._tokens:
            del cls._tokens[token]
            
            # 从数据库中也移除
            try:
                conn = sqlite3.connect(current_app.config['DB_PATH'])
                cursor = conn.cursor()
                cursor.execute('UPDATE users SET token = NULL WHERE token = ?', (token,))
                conn.commit()
                conn.close()
                return True
            except Exception as e:
                print(f"从数据库移除token出错: {str(e)}")
                return False
        return False 